使用 ws和ipc 协议进行消息订阅 发表于 2018-07-11 | 分类于 BlockChain | | 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465const Net = require('net');const Web3 = require("web3");// 设置 Provider, 使用 Infura, 自建 Rinkeby 节点的 ws/ipc 方式//const wsProvider = new Web3.providers.WebsocketProvider("wss://rinkeby.infura.io/ws");const wsProvider = new Web3.providers.WebsocketProvider("ws://www.xxx.com:1222", { headers: {Origin: "http://www.xxx.com"}});//const wsProvider = new Web3.providers.IpcProvider("/Users/xxx/rinkeby/data/geth.ipc", Net);// 设置 provider 给 web3const web3 = new Web3(wsProvider);// 订阅 syncing 状态, 测试没有成功, 无法获取数据const subscriptionSync = web3.eth.subscribe("syncing", (err, sync) => { //console.log("\n\n\nSyncing ==== %j ", sync, err);}).on("data", sync => { console.log("Syncing Data %j ", sync);}).on("changed", isSyncing => { console.log("Syncing isSyncing %s", isSyncing);}).on("error", err => { console.error("Syncing Error: ", err);});// 订阅 block 块状态const subscriptionBlock = web3.eth.subscribe("newBlockHeaders", (err, blockHeader) => { //console.log("\n\n\nBlockHeader ==== %j ", blockHeader, err);}).on("data", blockHeader => { console.log("Block Data %j ", blockHeader);}).on("error", err => { console.error("Block Error: ", err);});// 订阅 event 日志信息const subscriptionLog = web3.eth.subscribe("logs", {}, (err, log) => { //console.log("\n\n\nLogs ==== %j ", log, err);}).on("data", log => { // 本信息包含 pending 状态的数据, 出错后更正的数据 console.log("Logs Data %j", log);}).on("changed", log => { // 由于上面包含 pending 状态的信息, 那么挖矿后可能出现某些交易未成功, 导致原有 pending 状态的数据有变化, // 那么在此重新发送有问题的数据并且标记为 removed true, 同时更新后的数据将仍由上面的 data 事件捕获. console.log("Logs Changed %j", log);}).on("error", err => { console.error("Logs Error: ", err);});// 监听 pending 状态的交易.const subscriptionPending = web3.eth.subscribe("pendingTransactions", (err, transactionHash) => { //console.log("\n\n\nPending ==== %s ", transactionHash, err);}).on("data", transactionHash => { console.log("Pending Data %s", transactionHash);}).on("error", err => { console.error("Pending Error: ", err);}); Donate - Support to make this site better.捐助 - 支持我让我做得更好. 打赏 比特币(BTC/USDT) 以太坊(ETH/USDx) TRX(USDx)